package rack.lite.model

import rack.lite.utils.DbManager as db
import rack.lite.view.Console as con
/**
 *
 * @author atila
 */
@Singleton class DisciplinaDao {

   private static String table = "disciplina.table"
   private static String tmpTable = "disciplina.table.tmp"

   def create(Disciplina disc) {
      def f = db.getTable(table)
      println "\n\t[d] Debug: ${disc.toLine()}\n"
      f.append(disc.toLine())
      println "${con.info} Disciplina criada com sucesso.\n"
   }

   def delete(int codigo) {
      if (exists(codigo)) {
         def list = findAll()
         def tmp = db.getTable(tmpTable)
         list.each { disc ->
            if (disc?.codigo != codigo) {
               tmp.append(disc.toLine())
            }
         }
         def f = db.getTable(table)
         f.delete()
         tmp.renameTo(new File(table))
         println "${con.info} Disciplina ${codigo} deletada com sucesso.\n"
      } else {
         println "${con.warning} Disciplina ${codigo} não existe na base de dados.\n"
      }
   }

   def list() {
      def list = findAll()
      list.each {
         println it
      }
   }

   def exists(int codigo) {
      Disciplina d = new Disciplina(codigo:codigo)
      def list = findAll()
      if (list.lastIndexOf(d) == -1) {
         return false
      }
      return true
   }

   def findAll() {
      def list = []
      def f = db.getTable(table)
      def lines = f.readLines()
      lines.each {
         def a = it.split(":")
         Disciplina d = new Disciplina(codigo:a.getAt(0).toInteger(), nome:a.getAt(1), curso:a.getAt(2))
         list.push(d)
      }
      return list
   }
}

